<template>
  <a-layout class="s-bg-white f-h-100">
    <a-layout-header style="background: #fff; padding: 12px; line-height: 0; height: auto">
      <div class="btn-container">
        <u-icon-button itype="add" @click="openDialog('add')">新增类别</u-icon-button>
      </div>
    </a-layout-header>
    <a-layout-content class="f-padding-rl12">
      <u-table rowKey="id"
        :data="list"
        :columns="tableColumns"
        :loading="listLoading"
        :indentSize="36"
        defaultExpandAllRows>
      </u-table>
    </a-layout-content>

    <!-- 编辑类别 -->
    <u-dialog
      :title="titleMap[dialogStatus]"
      v-model:open="dialogVisible"
      width="630px"
      destroyOnClose 
      @submit="onOk(dialogStatus)"
      @close="dialogVisible = false">
      <a-form
        ref="dataForm"
        :rules="rules"
        :model="formData"
        label-width="110px"
        class="dialog-form"
      >
        <a-form-item label="类别名称" name="name">
          <a-input v-model:value="formData.name" placeholder="请输入类别名称" />
        </a-form-item>
        <a-form-item label="所属上级" name="parentId">
          <a-tree-select
            class="tree"
            v-model:value="formData.parentId"
            :tree-data="treeData"
            :fieldNames="{label: 'name', value: 'id'}"
            placeholder="请选择所属上级"
          ></a-tree-select>
        </a-form-item>
      </a-form>
    </u-dialog>
  </a-layout>
</template>

<script lang="ts" setup>
import { flowSortTree, deleteFlowSort, saveFlowSort, addFlowSort } from '@bs/process/flowsort';
import { ref, reactive, onMounted, nextTick, h } from 'vue';
import { messageC, clearObj } from '@/util/common'
import { ColumnProps } from 'ant-design-vue/es/table';
import { Button, Popconfirm, Space, } from 'ant-design-vue';

defineOptions({ name: 'user-manage' })

const titleMap = {
  add: '新增',
  edit: '编辑',
  view: '查看'
}

const list = ref([])
let pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 50,
  showTotal: total => `共 ${total} 条`
})
const listLoading = ref(false)
const searchForm = reactive({
  page: 1,
  pagesize: 10,
  name: ''
})
const tableColumns: Array<ColumnProps> = [
  { title: '序号', dataIndex: 'index', 
    customRender: ({text, record, index, column}) => {
      return index + 1
    }
  },
  { title: '类型名称', dataIndex: 'name', align: 'left' },
  { title: '类型编号', dataIndex: 'id' },
  { title: '操作', dataIndex: 'operation', width: '200px', align: 'center',
    customRender: ({ record, text }) => {
      return h(Space, [
        h(Button, { type: 'link', onClick: () => openDialog('edit', record) }, '编辑'),
        h(Popconfirm, { title: '您确定要删除吗？', onConfirm: () => deleteById(record),},
          [
            h(Button, { type: 'link' }, '删除')
          ]
        )
      ])
    }
  }
]

const dialogVisible = ref(false)
const dialogStatus = ref('add')
const dataForm = ref()
const formData = reactive({
  id:'',
  name: '',
  parentId: null
})

const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
}

const treeData = ref([])

onMounted(() => {
  getList()
})

// 获取
function getList() {
  listLoading.value = true;
  flowSortTree(searchForm).then((res) => {
    if (res.error === 200) {
      list.value = res.result;
      pagination.total = res.result.length;
    } else {
      messageC(`获取列表失败`, 'error');
    }
    listLoading.value = false;
  });
}

function search(type) {
  searchForm.page = 1;
  getList();
}

// 获取下拉框数据
function getSelectData() {
  flowSortTree().then((res) => {
    if (res.error === 200) {
      const data = res.result;
      data.forEach((x) => {
        x.children.forEach((y) => (y.disabled = true));
      });
      treeData.value = data;
    } else {
      messageC('获取失败', 'error');
    }
  });
}

function openDialog(action, row) {
  getSelectData();
  clearObj(formData);
  dialogStatus.value = action;
  dialogVisible.value = true;
  nextTick(() =>  {
    dataForm.value.clearValidate();
    if (action !== 'add') {
      formData.id = row.id;
      formData.name = row.name;
      if(row.parentId=="0") {
        formData.parentId = null;
      }
      else {
        formData.parentId = row.parentId;
      }
    }
  })
}

async function onOk(action) {
  if(formData.parentId==''||formData.parentId==null||formData.parentId==undefined){
    formData.parentId=0;
  }
  const valid = await dataForm.value.validate()
  if(valid) {
    const res = action === 'add' ? await addFlowSort(formData) : await saveFlowSort(formData);
    if (res.error === 200) {
      messageC(`${titleMap[action]}成功`, 'success');
      dialogVisible.value = false;
      search('reset');
    } else {
      messageC(`${titleMap[action]}失败`, 'error');
    }
  }
}

async function deleteById(row) {
  const res = await deleteFlowSort(row);
  if (res.error === 200) {
    messageC(`删除成功`, 'success');
    search('reset');
  } else {
    messageC(`删除失败`, 'error');
  }
}
</script>
